import { Request, Response } from 'express';
import { Op } from 'sequelize';
import Brand from '../models/Brand';
import { successResponse, errorResponse } from '../utils/response';
import { asyncHandler } from '../utils/asyncHandler';

class BrandController {
  /**
   * 创建商品品牌
   */
  createBrand = asyncHandler(async (req: Request, res: Response) => {
    const { 
      name, 
      logo, 
      description, 
      website, 
      sortOrder = 0, 
      isShow = 1 
    } = req.body;

    // 检查品牌名称是否重复
    const existingBrand = await Brand.findOne({
      where: { name }
    });

    if (existingBrand) {
      return errorResponse(res, '品牌名称已存在', 400);
    }

    const brand = await Brand.create({
      name,
      logo,
      description,
      website,
      sortOrder,
      isShow
    });

    return successResponse(res, brand, '创建品牌成功', 200);
  });

  /**
   * 获取品牌列表（分页）
   */
  getBrandList = asyncHandler(async (req: Request, res: Response) => {
    // 处理前端传递的嵌套参数
    const queryParams = (req.query as any).params || req.query;
    const { 
      page = 1, 
      pageSize = 10, 
      keyword = '', 
      isShow = '' 
    } = queryParams;

    const offset = (Number(page) - 1) * Number(pageSize);
    const limit = Number(pageSize);

    // 构建查询条件
    const whereCondition: any = {};

    if (keyword) {
      whereCondition[Op.or] = [
        { name: { [Op.like]: `%${keyword}%` } },
        { description: { [Op.like]: `%${keyword}%` } }
      ];
    }

    if (isShow !== '') {
      whereCondition.isShow = Number(isShow);
    }

    const { count, rows } = await Brand.findAndCountAll({
      where: whereCondition,
      order: [['sortOrder', 'ASC'], ['createdAt', 'DESC']],
      offset,
      limit
    });

    const result = {
      list: rows,
      total: count,
      page: Number(page),
      pageSize: Number(pageSize),
      totalPages: Math.ceil(count / Number(pageSize))
    };

    return successResponse(res, result, '获取品牌列表成功', 200);
  });

  /**
   * 获取品牌详情
   */
  getBrandDetail = asyncHandler(async (req: Request, res: Response) => {
    const { id } = req.params;

    const brand = await Brand.findByPk(id);

    if (!brand) {
      return errorResponse(res, '品牌不存在', 404);
    }

    return successResponse(res, brand, '获取品牌详情成功', 200);
  });

  /**
   * 更新品牌
   */
  updateBrand = asyncHandler(async (req: Request, res: Response) => {
    const { id } = req.params;
    const { 
      name, 
      logo, 
      description, 
      website, 
      sortOrder, 
      isShow 
    } = req.body;

    const brand = await Brand.findByPk(id);

    if (!brand) {
      return errorResponse(res, '品牌不存在', 404);
    }

    // 检查品牌名称是否重复（排除当前品牌）
    if (name) {
      const existingBrand = await Brand.findOne({
        where: {
          id: { [Op.ne]: id },
          name: name
        }
      });

      if (existingBrand) {
        return errorResponse(res, '品牌名称已存在', 400);
      }
    }

    await brand.update({
      name: name || brand.name,
      logo: logo || brand.logo,
      description: description || brand.description,
      website: website || brand.website,
      sortOrder: sortOrder !== undefined ? sortOrder : brand.sortOrder,
      isShow: isShow !== undefined ? isShow : brand.isShow
    });

    return successResponse(res, brand, '更新品牌成功', 200);
  });

  /**
   * 删除品牌
   */
  deleteBrand = asyncHandler(async (req: Request, res: Response) => {
    const { id } = req.params;

    const brand = await Brand.findByPk(id);

    if (!brand) {
      return errorResponse(res, '品牌不存在', 404);
    }

    await brand.destroy();

    return successResponse(res, null, '删除品牌成功', 200);
  });

  /**
   * 批量删除品牌
   */
  batchDeleteBrands = asyncHandler(async (req: Request, res: Response) => {
    const { ids } = req.body;

    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return errorResponse(res, '请选择要删除的品牌', 400);
    }

    const deletedCount = await Brand.destroy({
      where: {
        id: {
          [Op.in]: ids
        }
      }
    });

    return successResponse(res, { deletedCount }, `成功删除 ${deletedCount} 个品牌`, 200);
  });

  /**
   * 更新品牌显示状态
   */
  updateBrandStatus = asyncHandler(async (req: Request, res: Response) => {
    const { id } = req.params;
    const { isShow } = req.body;

    const brand = await Brand.findByPk(id);

    if (!brand) {
      return errorResponse(res, '品牌不存在', 404);
    }

    await brand.update({ isShow });

    return successResponse(res, brand, '更新品牌状态成功', 200);
  });

  /**
   * 获取所有显示的品牌（用于下拉选择）
   */
  getAllVisibleBrands = asyncHandler(async (req: Request, res: Response) => {
    const brands = await Brand.findAll({
      where: { isShow: 1 },
      order: [['sortOrder', 'ASC'], ['name', 'ASC']],
      attributes: ['id', 'name', 'logo']
    });

    return successResponse(res, brands, '获取品牌选项成功', 200);
  });

  /**
   * 获取品牌统计信息
   */
  getBrandStats = asyncHandler(async (req: Request, res: Response) => {
    const totalBrands = await Brand.count();
    const visibleBrands = await Brand.count({ where: { isShow: 1 } });
    const hiddenBrands = await Brand.count({ where: { isShow: 0 } });

    const stats = {
      total: totalBrands,
      visible: visibleBrands,
      hidden: hiddenBrands
    };

    return successResponse(res, stats, '获取品牌统计成功', 200);
  });
}

export default new BrandController();